﻿@using CID.Web.Support
@model CID.Web.Models.Development.VersionViewModel

<div id="Tabs">
    <ul>
        <li><a href="#General">General</a></li>
        <li><a href="#Dependencies">Dependencies</a></li>
        <li><a href="#DeploymentParameters">Deployment Parameters</a></li>
    </ul>
    <div id="General">
        @using (Html.BeginForm()) {
            @Html.ValidationSummary(true)
            <div class="editor-label">
                @Html.LabelFor(m => m.Name)
            </div>
            <div class="editor-field">
                @Html.KOTextBoxFor(m => m.Name)
                @Html.ValidationMessageFor(m => m.Name)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Description)
            </div>
            <div class="editor-field">
                @Html.KOTextAreaFor(m => m.Description)
                @Html.ValidationMessageFor(m => m.Description)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.DeploymentTemplate)
            </div>
            <div class="editor-field">
                @Html.KODropDownListForEntity(m => m.DeploymentTemplateId, Model.AvailableDeploymentTemplates, Model.DeploymentTemplateId, new { onchange = "javascript: OnDeploymentTemplateChanged(this);" })
                @Html.ValidationMessageFor(m => m.DeploymentTemplateId)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Release)
            </div>
            <div class="editor-field">
                @Html.KODropDownListForEntity(m => m.ReleaseId, Model.AvailableReleases, Model.ReleaseId)
                @Html.ValidationMessageFor(m => m.ReleaseId)
            </div>

            @Html.HiddenFor(m => m.ComponentId)
        }
    </div>
    <div id="Dependencies">
        <div class="editor-label">
            Component
        </div>
        <div class="editor-field">
            <select data-bind="options: AvailableDependencies, optionsText: 'Value', optionsText: 'Name', value: SelectedDependency, optionsCaption: 'Select...'"></select>
        </div>
        <p> 
            <input type="button" value="Add" data-bind="click: AddDependency" />
        </p>
        <table>
            <thead>
                <tr>
                    <th>
                        Component
                    </th>
                    <th>
                    </th>
                </tr>
            </thead>
            <tbody data-bind="template: {name: 'DependencyDisplayTemplate', foreach: DependsOn}">
            </tbody>
        </table>
    </div>
    <div id="DeploymentParameters">
        @{ViewBag.EditorId = "DeploymentParameterValues"; }
        @Html.Partial("ParameterValuesEditor")
    </div>

    <p>
        <!--TODO: this is not the best option, since is not using KO bindings, but is a hotfix for getting the button always visible. An alternative should be found-->
        <input type="button" value="Save" onclick="javascript: viewModel.Save();"/>
    </p>
</div>
<div>
    @Html.ActionLink("Back to List", "Versions", new { id = Model.ComponentId })
</div>

<script id="DependencyDisplayTemplate" type="text/x-jquery-tmpl">
    <tr>
        <td>${Name}</td>
        <td><input type="button" value="Delete" data-bind="click: Delete" /></td>
    </tr>
</script>
@Html.Partial("ParameterValuesEditionHelper")

<script type="text/javascript">
    $(document).ready(function () {
        $("#Tabs").tabs({
            select: function(event, ui) { setTimeout( function() { $('.parameter-values-group').accordion('resize'); }, 10) }
        });
        viewModel.Load();

        ko.bindingHandlers.fadeVisible = new FadeVisibleHandler();
        ko.applyBindings(viewModel.DeploymentParameterValuesList, document.getElementById("DeploymentParameterValues"));
        ko.applyBindings(viewModel, document.getElementById("General"));
        ko.applyBindings(viewModel, document.getElementById("Dependencies"));
        $(".parameter-values-group").accordion( {fillSpace: true} );
    });

    function OnDeploymentTemplateChanged(source) {
        var selectedTemplateId = source.options[source.selectedIndex].value;
        if((selectedTemplateId != 0) && (selectedTemplateId == viewModel.OriginalDeploymentTemplateId()))
            EnableDeploymentParametersTabs();
        else 
            DisableDeploymentParametersTabs();
    }

    function EnableDeploymentParametersTabs() {
        $("#Tabs").tabs("enable", 2);
    }

    function DisableDeploymentParametersTabs() {
        $("#Tabs").tabs("disable", 2);
    }

    function MapDependency(options)
    {
        var dependency = options.data;
        return new Dependency(dependency.Id, dependency.Name);
    }

    function Dependency(id, name)
    {
        this.Id = ko.observable(id);
        this.Name = ko.observable(name);
        this.Delete = function() { viewModel.RemoveDependency(this); };
    }

    var viewModel = {
        Id: ko.observable(),
        Name: ko.observable(),
        Description: ko.observable(),
        ReleaseId: ko.observable(),
        OriginalDeploymentTemplateId: ko.observable(),
        DeploymentTemplateId: ko.observable(),
        DeploymentParameterValues: ko.observableArray([]),
        DependsOn: ko.observableArray([]),
        SelectedDependency: ko.observable(),
        AvailableDependencies: ko.observableArray([]),
        RemoveDependency: function(dependency){
            this.DependsOn.remove(dependency);
        },
        AddDependency: function(){
            this.DependsOn.push(new Dependency(this.SelectedDependency().Id(), this.SelectedDependency().Name()));
            this.SelectedDependency(null);
        },
        Load: function () {
            var mapping = {
                'DeploymentParameterValues': {
                    create: function (options) { return MapParameterValue(options); }
                },
                'DependsOn': {
                    create: function (options) { return MapDependency(options); }
                },
                'AvailableDependencies': {
                    create: function (options) { return MapDependency(options); }
                }
            }
            ko.mapping.fromJS(@Html.JSON(Model), mapping, this);
            if(this.DeploymentTemplateId() == 0) this.DeploymentParameterValues = ko.observableArray([]); //When creating a new Version, there're no parameter values
            this.DeploymentParameterValuesList = new ParameterValuesList(this.DeploymentParameterValues());
            this.OriginalDeploymentTemplateId(this.DeploymentTemplateId());
        },
        Save: function () {
            var viewModelJSON = ko.toJSON(ko.mapping.toJS(this));
            $.ajax({
                url: this.PostUrl(),
                data: viewModelJSON,
                type: 'POST',
                contentType: 'application/json;',
                dataType: 'json',
                success: function (response) {
                    switch (response.Type) {
                        case "Redirect":
                            window.location.href = response.Url;
                            break;
                        case "View":
                            //TODO: display error in the summary error pane. Need to research how that's done with unobtrusive validation
                            alert(response.ModelError);
                            break;
                    }
                }
            });
        }
    };

</script>